package yt.kpool.activity.setting.agent.rebatesettlement;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yt.kpool.R;
import yt.kpool.adapter.RebateSettlementAdapter;
import yt.kpool.bean.CurrencyList;
import yt.kpool.bean.RebateSettlementBean;
import yt.kpool.network.HttpUtils;
import yt.kpool.network.MyGson;
import yt.kpool.network.NetHelperNew;
import yt.kpool.util.NetWorkUtil;
import yt.kpool.util.ToastUtil;
import yt.kpool.util.imageUtil.GlideUtil;
import yt.kpool.view.dialog.ErrorDialog;
import yt.kpool.view.dialog.LoadingDialog;
import yt.kpool.view.pop.CurrencyPopupWindow;


/**
 * 返点结算
 */
public class RebateSettlementAc extends AppCompatActivity {
    @BindView(R.id.ll_currency)
    LinearLayout ll_currency;
    //币种
    @BindView(R.id.tv_currrncyname)
    TextView tv_currrncyname;
    @BindView(R.id.iv_curreney)
    ImageView iv_curreney;
    @BindView(R.id.tv_startTime)
    TextView tv_startTime;
    @BindView(R.id.tv_endTime)
    TextView tv_endTime;
    private int currencyId=0;//币种id
    private List<CurrencyList.DataBean> currencyListData;
    private LoadingDialog loadingDialog;
    private CurrencyPopupWindow currencyPopupWindow;//币种选择

    private TimePickerView pvTimeDay;//年月日时间选择器
    private String NowData="";
    private SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
    private int startOrEnd = 0;//1 开始时间 2 结束时间

    @BindView(R.id.recyleview)
    LRecyclerView mRecyclerView;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private RebateSettlementAdapter rebateSettlementAdapter;
    private List<RebateSettlementBean.DataBean> list;
    private int pageIndex=1;
    private int kind=1;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_rebatesettlement);
        ButterKnife.bind(this);
        initView();
        getCurrrencyData();
    }

    /**
     * 获取返点结算列表数据
     */
    private void getNetData()
    {
        if(kind==1)
        loadingDialog.show();
        NetHelperNew.ProportionStatementList(currencyId + "", StartTime(), EndTime(), pageIndex + "", new HttpUtils.HttpCallback() {
        @Override
        public void onSuccess(String data) {
            if(kind==1)
            {
                loadingDialog.dismiss();
            }
            else
            {
                mRecyclerView.refreshComplete(10);
            }

            RebateSettlementBean rebateSettlementBean = MyGson.getInstance().fromJson(data, RebateSettlementBean.class);
            if(rebateSettlementBean.getType()==1)
            {
                if(rebateSettlementBean.getData().size()>0)
                {
                    list.addAll(rebateSettlementBean.getData());
                    rebateSettlementAdapter.setListData(list);
                    rebateSettlementAdapter.notifyDataSetChanged();
                }
                else
                {
                    ToastUtil.showToast(RebateSettlementAc.this,"没有可查询数据");
                }

            }
            else
            {
                ToastUtil.showToast(RebateSettlementAc.this,rebateSettlementBean.getContent());
            }

        }

        @Override
        public void onError(String msg) {
            super.onError(msg);
            if(kind==1)
            {
                loadingDialog.dismiss();
            }
            else
            {
                mRecyclerView.refreshComplete(10);
            }
            ToastUtil.showToast(RebateSettlementAc.this,msg);
        }
    });


    }

    private String StartTime()
    {
        return tv_startTime.getText().toString();
    }

    private String EndTime()
    {
        return tv_endTime.getText().toString();
    }

    private void initView()
    {
        loadingDialog = new LoadingDialog(RebateSettlementAc.this, 0);
        currencyListData = new ArrayList<>();
        //时间选择器

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -30);
        Date date = calendar.getTime();
        tv_startTime.setText(ymd.format(date));
        tv_endTime.setText(ymd.format(new Date(System.currentTimeMillis())));
              pvTimeDay = new TimePickerView(RebateSettlementAc.this, TimePickerView.Type.YEAR_MONTH_DAY);
        //设置范围
        pvTimeDay.setRange(2017, 2030);

        //设置是否循环滚动
        pvTimeDay.setCyclic(false);
        pvTimeDay.setCancelable(true);

        //时间选择后回调
        pvTimeDay.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                if (startOrEnd == 1) {
                    tv_startTime.setText(ymd.format(date));
                } else if (startOrEnd == 2) {
                    tv_endTime.setText(ymd.format(date));
                }


            }


        });
        NowData = ymd.format(new Date(System.currentTimeMillis()));
       // tv_FullName.setText(NowData);

        list=new ArrayList<>();
        rebateSettlementAdapter=new RebateSettlementAdapter(RebateSettlementAc.this,list);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(rebateSettlementAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader); //设置下拉刷新Progress的样式
        // mRecyclerView.setArrowImageView(R.drawable.iconfont_downgrey);  //设置下拉刷新箭头
        //设置头部加载颜色
        mRecyclerView.setHeaderViewColor(R.color.system_color, R.color.system_color, android.R.color.white);
//设置底部加载颜色
        mRecyclerView.setFooterViewColor(R.color.system_color, R.color.system_color, android.R.color.white);
        mRecyclerView.setAdapter(lRecyclerViewAdapter);
        mRecyclerView.setLoadMoreEnabled(true);
        //分割线
        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.d_13)
                .setColorResource(R.color.transparent)
                .build();
        mRecyclerView.addItemDecoration(divider);

        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                list.clear();
                kind=2;
                pageIndex=1;
                getNetData();

            }
        });
        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if(list.size()>=10)
                {
                    pageIndex++;
                    kind=2;
                    getNetData();
                }
                else
                    mRecyclerView.refreshComplete(10);

            }
        });
    }

    /**
     * 获取币种数据
     */
    private void getCurrrencyData() {

        if (NetWorkUtil.check(RebateSettlementAc.this)) {
            loadingDialog.show();

            NetHelperNew.GetCurrencyList(new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    loadingDialog.dismiss();
                    Log.i("-->", "币种列表：" + data);
                    CurrencyList currencyList = MyGson.getInstance().fromJson(data, CurrencyList.class);
                    if (currencyList.getType() == 1) {
                        currencyListData.addAll(currencyList.getData());
                        initCurrencyPopupWindow();
                        if (currencyList.getData().size() > 0) {
                            if (currencyId == 0) {
                                GlideUtil.loadImage(RebateSettlementAc.this, NetHelperNew.URL + currencyList.getData().get(0).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                                tv_currrncyname.setText(currencyList.getData().get(0).getCode().toUpperCase());
                                currencyId = currencyList.getData().get(0).getId();

                            } else {

                                for (int i = 0; i < currencyList.getData().size(); i++) {
                                    if (currencyId == currencyList.getData().get(i).getId()) {
                                        GlideUtil.loadImage(RebateSettlementAc.this, NetHelperNew.URL + currencyList.getData().get(i).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                                        tv_currrncyname.setText(currencyList.getData().get(i).getCode().toUpperCase());
                                    }
                                }
                            }
                        }
                        getNetData();
                    } else {
                        new ErrorDialog(RebateSettlementAc.this, currencyList.getContent()).show();
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);
                    loadingDialog.dismiss();

                    ToastUtil.showToast(RebateSettlementAc.this, msg);
                }
            });


        }

    }
    /**
     * 币种选择pop初始化
     */
    private void initCurrencyPopupWindow() {
        currencyPopupWindow = new CurrencyPopupWindow(currencyListData, RebateSettlementAc.this, new CurrencyPopupWindow.OnSeleCurrencyLayoutListener() {
            @Override
            public void selectHouseLayout(int i) {
                currencyId = currencyListData.get(i).getId();
                GlideUtil.loadImage(RebateSettlementAc.this, NetHelperNew.URL + currencyListData.get(i).getIcon(), iv_curreney, R.mipmap.failimage, R.mipmap.failimage);
                tv_currrncyname.setText(currencyListData.get(i).getCode().toUpperCase());
                list.clear();
                pageIndex=1;
                kind=1;
                getNetData();
            }
        });
    }
    @OnClick({R.id.title_left,R.id.title_center,R.id.ll_currency,R.id.ly_start_time,R.id.ly_end_time,R.id.search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left://返回
                finish();
                break;
            case R.id.title_center://返回
                finish();
                break;
            case R.id.ll_currency://选择币种
                if (currencyPopupWindow != null)
                    currencyPopupWindow.showAsDropDown(ll_currency, 0, 0);
                break;
            case R.id.ly_start_time://开始时间
                startOrEnd = 1;
                pvTimeDay.setTime(getFormatDate(tv_startTime.getText().toString()));
                pvTimeDay.show();
                break;
            case R.id.ly_end_time://结束时间
                startOrEnd = 2;
                pvTimeDay.setTime(getFormatDate(tv_endTime.getText().toString()));
                pvTimeDay.show();
                break;
            case R.id.search://搜索
                list.clear();
                pageIndex=1;
                kind=1;
                getNetData();
                break;
        }
    }

    /**
     * 转化时间
     *
     * @param s
     * @return
     */
    private Date getFormatDate(String s) {
        try {
            return ymd.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
